package com.alexander.cloundexplorer.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.alexander.cloundexplorer.R;
import com.alexander.cloundexplorer.adapter.ChildFilesAdapter;
import com.alexander.cloundexplorer.bean.params.GetAllChildFileParams;
import com.alexander.cloundexplorer.bean.params.UploadFileParams;
import com.alexander.cloundexplorer.bean.params.User;
import com.alexander.cloundexplorer.bean.response.BaseResponse;
import com.alexander.cloundexplorer.bean.response.FileAndDirectoryInfoResponse;
import com.alexander.cloundexplorer.bean.response.FileInfoResponse;
import com.alexander.cloundexplorer.codec.digest.DigestUtils;
import com.alexander.cloundexplorer.dialog.DirectoryOptionsDialog;
import com.alexander.cloundexplorer.dialog.FileOptionsDialog;
import com.alexander.cloundexplorer.util.Constants;
import com.alexander.cloundexplorer.util.UriTranslateUtil;
import com.alibaba.fastjson.JSON;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * @author Administrator
 * 展示文件列表0的页面,没有分类，根据传入的文件夹ID
 * （“ID是 0”说明是需要请求文件根目录）来请求数据进行展示
 */
public class FileListActivity extends BaseActivity implements ChildFilesAdapter.OnItemClickLisnter, FileOptionsDialog.OnDelLisnter
{
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private User user = new User();
    private FileAndDirectoryInfoResponse fileAndDirectoryInfoResponse;
    private List<FileAndDirectoryInfoResponse> list = new ArrayList<>();
    private ChildFilesAdapter childFilesAdapter;
    private GetAllChildFileParams getAllChildFileParams = new GetAllChildFileParams();
    private FileOptionsDialog fileOptionsDialog;
    private DirectoryOptionsDialog directoryOptionsDialog;
    private int selectFileRequestCode = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_filelist_layout);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        user = (User) intent.getExtras().getSerializable("user");
        fileAndDirectoryInfoResponse = (FileAndDirectoryInfoResponse) intent.getSerializableExtra("fileInfo");
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        childFilesAdapter = new ChildFilesAdapter(this, list);
        childFilesAdapter.setOnItemClickLisnter(this);
        recyclerView.setAdapter(childFilesAdapter);

        getAllChildFileParams.setAccount(user.getPhone());
        getAllChildFileParams.setPassword(user.getPassword());
        getAllChildFileParams.setFatherId(fileAndDirectoryInfoResponse.getId());
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        OkHttpUtils
                .post()
                .url(Constants.IP.concat("/fileController/getAllChildFile"))
                .addParams("params", JSON.toJSONString(getAllChildFileParams))
                .build()
                .execute(new StringCallback()
                {
                    @Override
                    public void onError(Call call, Exception e, int id)
                    {
                        showTip(e.getMessage());
                    }

                    @Override
                    public void onResponse(String response, int id)
                    {
                        showTip(response);
                        BaseResponse baseResponse = JSON.parseObject(response, BaseResponse.class);
                        list.removeAll(list);
                        list.addAll(JSON.parseArray(baseResponse.getData().toString(), FileAndDirectoryInfoResponse.class));
                        childFilesAdapter.notifyDataSetChanged();
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_options_filelist, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            /**上传文件*/
            case R.id.upload:
                Intent intent1 = new Intent(Intent.ACTION_GET_CONTENT);
                /**文件类型无限制*/
                intent1.setType("*/*");
                intent1.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent1, selectFileRequestCode);
                return true;
            /**新建文件夹*/
            case R.id.mkdir:
                Intent intent2 = new Intent(this, MkDirActivity.class);
                intent2.putExtra("data", fileAndDirectoryInfoResponse);
                intent2.putExtra("user", user);
                startActivity(intent2);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        String filePath = null;
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && requestCode == selectFileRequestCode && resultCode == Activity.RESULT_OK)
        {
            Uri uri = data.getData();
            if ("file".equalsIgnoreCase(uri.getScheme()))
            {
                filePath = uri.getPath();
            }
            UriTranslateUtil uriTranslateUtil = UriTranslateUtil.getInstance();
            /**4.4以后的获取路径方法*/
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT)
            {
                filePath = uriTranslateUtil.getPath(this, uri);
            } else
            {
                /**4.4以下下系统调用方法*/
                filePath = uriTranslateUtil.getRealPathFromURI(uri, FileListActivity.this);
            }
        }
        upload(filePath);
    }

    private void upload(String filePath)
    {
        try
        {
            File file = new File(filePath);
            UploadFileParams uploadFileParams = new UploadFileParams();
            uploadFileParams.setFileCount("1");
            uploadFileParams.setAccount(user.getPhone());
            uploadFileParams.setPassword(user.getPassword());
            FileInputStream fileInputStream = new FileInputStream(file);
            String md5 = DigestUtils.md5Hex(fileInputStream);
            uploadFileParams.setFileMD5(md5);
            uploadFileParams.setFatherDirectoryId(fileAndDirectoryInfoResponse.getId());
            String json = JSON.toJSONString(uploadFileParams);
            OkHttpUtils.post()
                    .url(Constants.IP.concat("/fileController/uploadFile"))
                    .addParams("params", json)
                    .addFile("file", file.getName(), file)
                    .build()
                    .connTimeOut(100000)
                    .readTimeOut(100000)
                    .writeTimeOut(100000)
                    .execute(new StringCallback()
                    {
                        @Override
                        public void onError(Call call, Exception e, int id)
                        {
                            System.out.println("出错出错出错");
                            e.printStackTrace();
                        }

                        @Override
                        public void onResponse(String response, int id)
                        {
                            System.out.println("上传成功");
                            System.out.println(response);
                        }
                    });
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(int position)
    {
        FileAndDirectoryInfoResponse info = list.get(position);
        if(info.getIsFile().equals("1"))
        {
            showTip("打开文件".concat(info.getStringName()));
        }else
        {
            Intent intent = new Intent(FileListActivity.this, FileListActivity.class);
            intent.putExtra("user", user);
            intent.putExtra("fileInfo", info);
            startActivity(intent);
        }
    }

    @Override
    public void onMoreClick(int position)
    {
        showTip("更多");
        FileAndDirectoryInfoResponse fileAndDirectoryInfoResponse1 = list.get(position);
        if(fileAndDirectoryInfoResponse1.getIsFile().equals("1"))
        {
            FileInfoResponse fileInfoResponse = fileAndDirectoryInfoResponse1.getFileInfo();
            fileOptionsDialog = new FileOptionsDialog(FileListActivity.this, fileInfoResponse, user);
            fileOptionsDialog.setOnDelLisnter(FileListActivity.this);
            fileOptionsDialog.show();
        }
        else
        {
            DirectoryOptionsDialog directoryOptionsDialog = new DirectoryOptionsDialog(FileListActivity.this, list.get(position).getDirectoryInfo(), user);
            directoryOptionsDialog.show();
        }
    }

    /**
     * 文件删除成功失败的回调
     */
    @Override
    public void onDelSuccess(String result, FileInfoResponse fileInfoResponse)
    {
        list.remove(fileInfoResponse);
        childFilesAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDelError(Throwable throwable)
    {
        showTip(throwable.getMessage());
    }

    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
        finish();
    }
}